package com.foton.bpc.all.util;

import lombok.SneakyThrows;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * @Author RenPu
 * @Date 2023/6/5 22:13
 * @Version 1.0
 * @Description: SPI工具类封装
 **/
public class URIUtils {


    /**
     * 根据key获取URI中路径的参数对应的值
     * 例如：http://127.0.0.1:8080/getMethond?name=张三&age=18
     * 根据name获取张三
     * @param uri
     * @param mark
     * @return
     * @throws UnsupportedEncodingException
     */


    @SneakyThrows
    public static String getParam(URI uri, String mark)  {
        Map<String, String> params = new HashMap<>();
        String query = uri.getQuery();

        if (query != null) {
            String[] pairs = query.split("&");

            for (String pair : pairs) {
                int idx = pair.indexOf("=");

                if (idx > 0) {
                    String key = URLDecoder.decode(pair.substring(0, idx), "UTF-8");
                    String value = URLDecoder.decode(pair.substring(idx + 1), "UTF-8");
                    params.put(key, value);
                }
            }
        }

        return params.get(mark);
    }


    /**
     * 根据URI，进行解析出全类名
     * @param serviceUri
     * @return
     */
    public static String getService(URI serviceUri) {
        String path = serviceUri.getPath(); // This will give you "/com.foton.bq.service.api.sms.SmsService"
        String serviceName = path.substring(1);
        return serviceName;
    }
}
